class StudentsController < ApplicationController
  def index
    @students = Student.all
  end

  def register
    @teachers = Teacher.all.collect{|x| [x.name,x.id]}
    if params[:student]
      @student = Student.new params[:student]
      @student.password = generate_pwd
      if @student.save
        redirect_to :action => 'index'
      else
        render :register
      end
    end
  end

  def show
    @student = Student.find(params[:id]) 
  end

  def edit
    @teachers = Teacher.all.collect{|x| [x.name, x.id]}
    @student = Student.find(params[:id])
    if params[:student]
      if @student.update_attributes(params[:student])
        redirect_to :action => 'index'
      else
        render "edit"
      end
    end
  end
  #学员付款
  def pay
    @student = Student.find(params[:id])
    @courses = Course.all.collect{|x| [x.name,x.id]}
    if params[:fee]
      @fee = StudentFee.new(params[:fee]) 
      if @fee.save
        #find course card for student
        @courseCard =CoursesStudent.find(:first,:conditions=>["student_id =? and course_id = ?",@student.id,params[:fee][:course_id]])
        if @courseCard
          #if a course card exists, update the ammount of the course
          _updatedAmount = @courseCard.amount + @fee.amount
          @courseCard.update_attribute("amount", _updatedAmount)
        else
          #create a new course card
          @courseCard = CoursesStudent.new
          @courseCard.student = @student
          @courseCard.course = @fee.course
          @courseCard.amount = @fee.amount
          @courseCard.save
        end
        redirect_to :action => 'show',:id=>@student
      end
    end
  end
  
  def destroy
    @student = Student.find(params[:id])
    @student.destroy
    redirect_to :action => 'index'
  end

  private 
  def generate_pwd
    return "12345"
  end
end
